package com.juicygames.framework.collider;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import android.graphics.Rect;

import com.juicygames.framework.action.EntityDestroyedAction;
import com.juicygames.framework.action.UpdateAction;
import com.juicygames.framework.gamepart.GameComponent;
import com.juicygames.framework.gamepart.GameEntity;
import com.juicygames.framework.gamepart.GameHandler;
import com.juicygames.framework.handler.UpdateHandler;
import com.juicygames.framework.property.space.CollisionBoundingBox;

public class Collider extends GameComponent {
	
	List<GameEntity> targetEntities;
	CollisionBoundingBox box;
	
	public void load() {
		super.load();
		addPart(new MyUpdateHandler());
		addPart(new MyEntityDestroyedHandler());
		
		targetEntities = new CopyOnWriteArrayList<GameEntity>();
		
		box = parent.getPart(CollisionBoundingBox.class);
	}
	
	public void watchEntity(GameEntity entity) {
		targetEntities.add(entity);
	}
	
	public class MyUpdateHandler extends UpdateHandler {
		public void handle(UpdateAction update) {
			for (GameEntity otherEntity : targetEntities) {
				if (boxesIntersect(box.rect, otherEntity.getPart(CollisionBoundingBox.class).rect)) {
					entity.handleAction(TargetCollisionAction.getInstance(otherEntity));
				}
			}
		}
		private boolean boxesIntersect(Rect r1, Rect r2) {
			Rect newR1 = new Rect(r1);
			return newR1.intersect(r2);
		}
	}
	
	public class MyEntityDestroyedHandler extends GameHandler<EntityDestroyedAction> {
		
		public void load() {
			groundHandler();
		}
		
		public Class<EntityDestroyedAction> getActionClassHandled() {
			return EntityDestroyedAction.class;
		}
		
		public void handle(EntityDestroyedAction entityDestroyed) {
			targetEntities.remove(entityDestroyed.getEntity());
		}
	}

}
